﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Sfs2X;
using Sfs2X.Core;
using Sfs2X.Entities;
using Sfs2X.Requests;
using Sfs2X.Logging;
using Sfs2X.Entities.Data;

public class GUIWait : MonoBehaviour {

    public GUIText status;

    private SmartFox sfConnectObj;
    private string sfStatus;

    void Awake() {
        if (SmartFoxConnection.IsInitialized)
        {
            sfConnectObj = SmartFoxConnection.Connection;
        }
        else
        {
            Application.LoadLevel("Connector");
        }

        // Register callback delegate
        sfConnectObj.AddEventListener(SFSEvent.CONNECTION_LOST, OnConnectionLost);
        sfConnectObj.AddEventListener(SFSEvent.EXTENSION_RESPONSE, OnExtensionResponse);
    }

	// Use this for initialization
	void Start () {
        SmartFoxConnection.Connection = sfConnectObj;
	}
	
	// Update is called once per frame
	void Update () {
	
	}

    void FixedUpdate()
    {
        sfConnectObj.ProcessEvents();
    }

    void OnConnectionLost(BaseEvent evt)
    {
        sfStatus = "Connection was lost, Reason: " + (string)evt.Params[MySFSParams.PARAM_REASON];
        status.text = sfStatus;
    }

    void OnExtensionResponse(BaseEvent evt)
    {
        Debug.Log("TV.Vinh User: extension response arrived");
        string cmd = evt.Params[MySFSParams.PARAM_CMD] as string;
        SFSObject dataObject = evt.Params[MySFSParams.PARAM_DATA] as SFSObject;
        
        switch (cmd)
        {
            // game will start after 5 seconds
            case "getReady":
                SmartFoxConnection.PersistentData = dataObject;
                StartCoroutine(countDown(5));
                break;
            // in this scene, it mean player's opponent has left while game is being start.
            case "win":
                StopAllCoroutines();
                status.text = "Sorry, your opponent has left this game. Game stopped!";
                break;
            case "start":
                UnregisterSFSSceneCallbacks();
                Application.LoadLevel("PlayGame");
                break;
        }
    }

    IEnumerator countDown(int time)
    {
        for (int i = time; i >= 0; i--)
        {
            yield return new WaitForSeconds(1);
            status.text = "Game will start in " + i + " seconds...";
        }
    }

    private void UnregisterSFSSceneCallbacks()
    {
        // This should be called when switching scenes, so callbacks from the backend do not trigger code in this scene
        sfConnectObj.RemoveAllEventListeners();
    }

    void OnDestroy() {
        UnregisterSFSSceneCallbacks();
    }
}
